<?php

namespace app\admin\controller;

use app\admin\model\ProductModel;
use app\admin\utils\cosOper;
use app\admin\utils\jsonResult;
use app\admin\utils\ontimeLog;
use app\admin\utils\uuidUtils;
use think\Controller;
use think\Exception;
use think\exception\DbException;
use think\Request;
use think\Db;


class Product extends Controller
{

    public function _initialize()
    {

    }

    /**********视图模板***********/

    public function product_list()
    {
        return $this->fetch('product_list');
    }

    public function product_add()
    {
        return $this->fetch('product_add');
    }

    public function image_upload()
    {
        return $this->fetch('image_zone/image_upload');

    }

    public function product_cate()
    {
        return $this->fetch('product_cate');
    }

    /**********JsonAPI接口***********/
    public function getProductList(): \think\response\Json
    {
        $page = input('param.page');
        $limit = input('param.limit');
        $param = [];
        empty(input('param.title')) ?: $param['product.title'] = ['like', '%' . input('param.title') . '%'];
        $productModel = new ProductModel();
        $dataList = $productModel->list($page, $limit, $param);
        $count = $productModel->count();

        return (new jsonResult)::result(0, "获取商品列表成功", $dataList, $count);
    }

    public function uploadProductStatus(Request $request): \think\response\Json
    {
        $id = $request->param('id');
        $status = $request->param('status');
        $productModel = new ProductModel();
        if ($productModel->uploadProductStatus($id, $status) == -1) {
            return (new jsonResult)::result(1, "修改产品状态失败");
        }
        return (new jsonResult)::result(0, "修改产品状态成功");
    }

    public function addProduct(Request $request): \think\response\Json
    {
        if (!$this->request->isPost()) {
            return (new jsonResult)::result(501, "添加失败 Post请求中的商品信息无效");
        }

        // 从post中获取json转换成数组
        $resJson = ($request->post());

        $title = empty($resJson['title']) ? '' : $resJson['title'];
        $price = empty($resJson['price']) ? '' : $resJson['price'];
        $cid = empty($resJson['cid']) ? '' : $resJson['cid'];
        $keywords = empty($resJson['keywords']) ? '' : $resJson['keywords'];
        $mainImage = empty($resJson['mainImage']) ? '' : $resJson['mainImage'];
        $secondaryImage = empty($resJson['secondaryImage']) ? '' : $resJson['secondaryImage'];
        $img = $mainImage;
        if (!empty($secondaryImage)) {
            foreach ($secondaryImage as $item) {
                $img = $img . ';' . $item;
            }
        }
        $desc = empty($resJson['desc']) ? '' : $resJson['desc'];
        $status = empty($resJson['status']) ? '' :
            ($resJson['status'] == 'on' ? 1 : 0);
        $skuData = empty($resJson['skuData']) ? [] : $resJson['skuData'];

//        ontimeLog::mylog('$skuData: ' . json_encode($skuData[0]['sku_title'], JSON_UNESCAPED_UNICODE), __FILE__, __METHOD__);

        //判断必填信息是否为空
        if (empty($title) || empty($price) || empty($cid) || empty($mainImage)) {
            return (new jsonResult)::result(1, "添加失败 缺少商品必填信息");
        }

        $data = [
            'cid' => $cid,
            'title' => $title,
            'pro_no' => uuidUtils::getUUID(),
            'keywords' => $keywords,
            'img' => $img,
            'price' => $price,
            'desc' => $desc,
            'pv' => 0,
            'status' => $status,
            'add_time' => date('Y-m-d h:i:s', time())
        ];


        $productModel = new ProductModel();

        Db::startTrans();
        try {
            $productModel->add($data);
            $product_id = Db::table('product')->getLastInsID();
            foreach ($skuData as $skuItem) {
                $skuItem['product_id'] = $product_id;
                $skuItem['add_time'] = date('Y-m-d h:i:s', time());
                $productModel->addSkuData($skuItem);
            }
            Db::commit();
            return (new jsonResult)::result(0, "上传成功");
        } catch (\ErrorException $e) {
            Db::rollback();
            ontimeLog::mylog(json_encode($e), __FILE__, __METHOD__);

            return (new jsonResult)::result(1, "插入数据库错误", json_encode($e));
        }
    }

    //todo 删除商品
//    public function deleteProductByMd5(Request $request): \think\response\Json
//    {
//        $md5 = $request->param('md5');
//        $productZoneModel = new productZoneModel();
//        Db::startTrans();
//        try {
//            $objKey = $productZoneModel->selectByMd5($md5)['key'];
//            ontimeLog::mylog("objKey：" . $objKey, __FILE__, __METHOD__);
//            $deleteRes = $productZoneModel->delete($md5) == 1;
//            ontimeLog::mylog("deleteRes：" . $deleteRes, __FILE__, __METHOD__);
//            if ($deleteRes) {
//                $cosOper = new cosOper();
//                if ($objKey != -1 && $cosOper->deleteObj($objKey)) {
//                    Db::commit();
//                    ontimeLog::mylog("COS对象删除成功：" . $md5, __FILE__, __METHOD__);
//                    return (new jsonResult)::result(200, "删除成功");
//                } else {
//                    Db::rollback();
//                    return (new jsonResult)::result(501, "删除失败 桶中未找到该数据");
//                }
//            }
//        } catch (\Exception $e) {
//            Db::rollback();
//            ontimeLog::mylog('删除失败：' . $e, __FILE__, __METHOD__);
//            return (new jsonResult)::result(501, "删除失败：" . $e);
//        }
//        return (new jsonResult)::result(501, "删除失败");
//    }


    public function getCatesList(): \think\response\Json
    {
        $productModel = new ProductModel();
        $dataList = $productModel->listCate();
        return (new jsonResult)::result(0, "获取分类列表成功", $dataList);
    }

    public function addCate(Request $request): \think\response\Json
    {
        $resJson = ($request->post());
        $title = empty($resJson['title']) ? '' : $resJson['title'];
        $pid = empty($resJson['pid']) ? '0' : $resJson['pid'];

        ontimeLog::mylog($title, __FILE__, __METHOD__);
        ontimeLog::mylog($pid, __FILE__, __METHOD__);
        if (empty($title) || $pid === null) {
            return (new jsonResult)::result(1, "添加失败 缺少商品必填信息");
        }

        $productModel = new ProductModel();

        $data = [
            'pid' => $pid,
            'title' => $title,
            'status' => 1,
            'add_time' => date('Y-m-d h:i:s', time())
        ];

        $productModel->addCate($data);
        return (new jsonResult)::result(0, "添加分类成功");
    }

    public function uploadCateStatus(Request $request): \think\response\Json
    {
        $id = $request->param('id');
        $status = $request->param('status');
        $productModel = new ProductModel();
        if ($productModel->uploadCateStatus($id, $status) == -1) {
            return (new jsonResult)::result(1, "修改分类状态失败");
        }
        return (new jsonResult)::result(0, "修改分类状态成功");
    }
}
